package cn.uce.cc.srv.biz.impl;

import cn.uce.base.exception.DuplicateKeyException;
import cn.uce.cc.api.service.biz.ICcAgentBiz;
import cn.uce.cc.entity.CcAgent;
import cn.uce.cc.srv.service.CcAgentService;
import cn.uce.web.common.base.CurrentUser;
import cn.uce.web.common.util.WebUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * Created by zhaocan on 2018/5/23.
 */
@Service("ccAgentBiz")
@Transactional(readOnly = true, rollbackFor = Exception.class)
public class CcAgentBiz implements ICcAgentBiz {

    @Resource
    private CcAgentService ccAgentService;

    @Override
    public CcAgent getCcAgentByUserId(String userId) {
        return ccAgentService.getCcAgentByUserId(userId);
    }

    @Override
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public int save(CcAgent ccAgent) {
        CurrentUser currentUser = WebUtil.getCurrentUser();
        if(currentUser.getEmpCode().isEmpty() || currentUser.getOrgId()==0){
            return -1;
        }else{
            ccAgent.setCreateEmp(currentUser.getEmpCode());
            ccAgent.setCreateOrg(currentUser.getOrgId());
            checkAgentRefUser(ccAgent);
            return ccAgentService.save(ccAgent);
        }
    }

    /**
     * 验证坐席是否被绑定
     * @param ccAgent
     */
    private void checkAgentRefUser(CcAgent ccAgent) {
        CcAgent ccAgengInfo = ccAgentService.getCcAgentByOpenId(ccAgent.getCtiOpenid());
        if(null != ccAgengInfo){
            throw new DuplicateKeyException("工号["+ccAgengInfo.getUserId()+"]已绑定坐席["+ccAgent.getCtiOpenid()+"]");
        }
    }

    @Override
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public int updateByCode(CcAgent ccAgent) {
        checkAgentRefUser(ccAgent);
        return ccAgentService.updateByCode(ccAgent);
    }

    @Override
    public CcAgent getCcAgentByOpenId(String openId) {
        return ccAgentService.getCcAgentByOpenId(openId);
    }
}
